package com.easyattendance.services;

import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.easyattendance.model.Student;
import com.easyattendance.model.StudentLeave;
import com.easyattendance.util.HibernateUtil;

public class StudentLeaveService {

	/* Method to CREATE leave detail in the database */
	   public synchronized boolean addStudentLeave(StudentLeave studentleave){
	      Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean result=false;
	      
	      try{
	         tx = session.beginTransaction();

	        	 session.save(studentleave);
	           	 tx.commit();
	         result=true;
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	     return result;
	   }
	   
	   public boolean ifAlreadyExists(StudentLeave newStudentLeave) {
			boolean flag = false;

			Session session = HibernateUtil.openSession();
			Transaction tx = null;
			List leaves = null;
			try {
				tx = session.beginTransaction();
				leaves = session.createQuery("FROM StudentLeave").list();
				for (Iterator iterator = leaves.iterator(); iterator.hasNext();) {
					StudentLeave leave = (StudentLeave) iterator.next();
					if (leave.equals(newStudentLeave)) {
						System.out.println("This leave details already exists");
						flag = true;
						break;
					}

				}
				tx.commit();
			} catch (HibernateException e) {
				if (tx != null)
					tx.rollback();
				e.printStackTrace();
			} finally {
				session.close();
			}

			return flag;

		}

		/* Method to  READ all the Leave details */
		   public List listStudentLeaves( ) {
			   Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List studentleaves = null;
		      try{
		         tx = session.beginTransaction();
		         studentleaves = session.createQuery("FROM StudentLeave").list(); 
		         for (Iterator iterator = studentleaves.iterator(); iterator.hasNext();){
		        	StudentLeave studentleave = (StudentLeave) iterator.next(); 
		            //System.out.print("Student Name: " +studentleave.ge); 
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
		      return studentleaves;
		   }
}
